package codeGen.core.jpa;

import codeGen.core.FreemarkerUtil;
import codeGen.core.model.FieldModel;
import codeGen.core.model.TableModel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

public class JpaModelGen {
    public static void genCode(TableModel tModel, File output) {
        try {
            List<FieldModel> primes = tModel.getPrimtives();
            if (primes.size() > 1) {
                //
                File id_class = new File(output, tModel.getToClassName() + "Id.java");
                FreemarkerUtil.genResource("jpa/composite_key.ftl", new FileOutputStream(id_class), tModel);
                tModel.setPrimeType(tModel.getToClassName() + "Id");
                tModel.setFieldPrime("pk");
                tModel.setHasCompositePk(true);
            } else if (primes.size() == 1) {
                //
                tModel.setPrimeType(tModel.getPrimtives().get(0).getJavaType());
                tModel.setPrimeTypeLowerCase(tModel.getPrimtives().get(0).getJavaType().toLowerCase());
                tModel.setFieldPrime(tModel.getPrimtives().get(0).getName());
                tModel.setHasCompositePk(false);
            } else {
                //
                tModel.setPrimeType(tModel.getToClassName());
                tModel.setFieldPrime("pk");
                tModel.setHasCompositePk(true);
            }

            File model_class = new File(output, tModel.getToClassName() + ".java");
            FreemarkerUtil.genResource("jpa/model.ftl", new FileOutputStream(model_class), tModel);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
